package com.unitd.frame.springweb.plugins.velocity.directive;

import com.unitd.frame.springweb.plugins.velocity.directive.OverrideDirective.OverrideNodeWrapper;
import org.apache.velocity.context.InternalContextAdapter;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.directive.Directive;
import org.apache.velocity.runtime.parser.node.Node;

import java.io.IOException;
import java.io.Writer;

/**
 * @desc 自定义一个Velocity的指令类, 用于一个子velocity页面在继承自父velocity页面的同时, 也继承父页面的相关节点的值
 * @filename SuperDirective.java
 * @copyright www.unitd.com
 * @author Hudan
 * @version 1.0
 * @date 2017/4/2
 */
public class SuperDirective extends Directive {
	public SuperDirective() {
	}

	@Override
	public String getName() {
		return "super";
	}

	@Override
	public int getType() {
		return 2;
	}

	@Override
	public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException {
		OverrideNodeWrapper current = (OverrideNodeWrapper) context.get(DirectiveUtil.OVERRIDE_CURRENT_NODE);
		if (current == null) {
			throw new ParseErrorException("#super direction must be child of override");
		} else {
			OverrideNodeWrapper parent = current.parentNode;
			if (parent == null) {
				throw new ParseErrorException("not found parent block for #super ");
			} else {
				return parent.render(context, writer);
			}
		}
	}
}